package ink.metoo.auto.fishpi.job

import com.google.gson.Gson
import ink.metoo.auto.fishpi.Log
import ink.metoo.auto.fishpi.call.BreezeMoonCall
import okhttp3.OkHttpClient
import okhttp3.Request

class GuessingRiddleGameJob : RunnableJob {

    val log = Log

    override fun run() {
        reloadGuessingRiddle()
        val gr = guessingRiddle!!
        val addBreezeMoonResult =
            BreezeMoonCall.addBreezeMoon("[积分谜语] ${gr.lx}-${gr.mt} 提示: ${gr.ts}-答案长度${gr.getSimpleMd().length} (在聊天室输入[解谜 答案]即可参与, 答对自动转账积分并且本条消息消失)")
        val data = addBreezeMoonResult.data
        if (data != null) {
            previousOid = data.oId
        }
        log.info("addBreezeMoonResult ${addBreezeMoonResult.code} oid: $previousOid")

    }


    class GuessingRiddle {
        val code: String? = null
        val mt: String? = null
        val md: String? = null
        val lx: String? = null
        val ts: String? = null


        fun getSimpleMd(): String {
            var md: String = md!!
            if (md.contains("(") || md.contains("（")) {
                val split = md.split("[(（]".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                md = split[0]
            }
            return md
        }
    }

    companion object {
        private const val API = "https://v.api.aa1.cn/api/api-miyu/index.php"
        private val okHttpClient = OkHttpClient()
        private val gson = Gson()
        var previousOid: String? = null
        var guessingRiddle: GuessingRiddle? = null

        fun reloadGuessingRiddle() {
            deletePreviousGuessingRiddle()
            var json: String = okHttpClient
                .newCall(
                    Request.Builder()
                        .get()
                        .url(API)
                        .build()
                ).execute().body!!.string()
            val split = json.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            json = split[split.size - 1].replace("\"\"", "\"")
            Log.info("GetGuessingRiddleGame Json: $json")
            guessingRiddle = gson.fromJson(json, GuessingRiddle::class.java)
        }


        fun deletePreviousGuessingRiddle() {
            val old = previousOid
            if (old != null) {
                BreezeMoonCall.deleteBreezeMoon(old)
            }
            guessingRiddle = null
            previousOid = null
        }
    }

}
